package org.chnxi.leetcode.problems.ques13;

/**
 * 罗马数字转整数
 * 执行用时 :5 ms, 在所有 Java 提交中击败了67.78%的用户
 * 内存消耗 :39.8 MB, 在所有 Java 提交中击败了5.56%的用户
 */
public class Simple01 {

    public static void main(String[] args) {
        String str1 = "III";
        int result1 = romanToInt(str1);
        System.out.println("str1="+result1);

        String str2 = "IV";
        int result2 = romanToInt(str2);
        System.out.println("str2="+result2);

        String str3 = "IX";
        int result3 = romanToInt(str3);
        System.out.println("str3="+result3);

        String str4 = "LVIII";
        int result4 = romanToInt(str4);
        System.out.println("str4="+result4);

        String str5 = "MCMXCIV";
        int result5 = romanToInt(str5);
        System.out.println("str5="+result5);

        String str6 = "XX";
        int result6 = romanToInt(str6);
        System.out.println("str6="+result6);

    }

    //定义罗马数字可能出现的情况
    final static String[] arr = {
            "M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"
    };

    //针对arr列举对应的值
    final static int[] nums = {
            1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
    };

    public static int romanToInt(String s) {
        //记录结果
        int result = 0;

        //遍历罗马字符的游标
        int idx = 0;

        while (idx < arr.length){
            //当前字符串匹配到罗马字符
            if(s.startsWith(arr[idx])){
                result += nums[idx];
                //当前字符串已经遍历完成
                if(s.length() <= arr[idx].length()){
                    break;
                }else{//处理剩余字符串
                    s = s.substring(arr[idx].length());
                }
            }else {
                //未匹配到，罗马字符游标++
                idx++;
            }
        }

        return result;

    }

}
